from django.template import Library, Node 
from django.db.models import get_model
from django.contrib.auth.models import User
from vidastream.stream.models import UserProfile, Feed

register = Library()

class LatestContentNode(Node):
	def __init__(self, model, num, varname):
		self.num, self.varname = num, varname
		# asterix is short for "use these results as your arguements"
		self.model = get_model(*model.split('.'))

	def render(self, context):
		context[self.varname] = self.model._default_manager.all()[:self.num]
		return ''

@register.tag
def get_latest(parser, token):
	"""
	get_latest <app.model> <number to retrieve> as <what to call them>
	
	this is the wrapper of the tag, it hands most everything off to LatestNode which is the guts of it all
	"""
 
	bits = token.contents.split()
	if len(bits) != 5:
		raise TemplateSyntaxError, "get_latest takes exactly four arguements"
	if bits[3] != 'as':
		raise TemplateSyntaxError, "fourth argument to the get_latest tag must be 'as'"
	return LatestContentNode(bits[1], bits[2], bits[4])


class LatestLivesNode(Node):
	def render(self, context):
		latest_lives = []
		user_profiles = UserProfile.objects.exclude(hidden=True).filter(user__is_active__exact=True)
		for user_profile in user_profiles:
			user = user_profile.user
			latest_lives.append(user)

		context['latest_lives'] = latest_lives

		return ''

def get_latest_lives(parser, token):
	bits = token.contents.split()
	if len(bits) != 1:
		raise TemplateSyntaxError, "get_latest_lives takes exactly 0 arguements"
	return LatestLivesNode()
register.tag('get_latest_lives', get_latest_lives)
